package hot;

import java.util.LinkedList;
import java.util.List;

/**
 * @author way
 * @create 2025-03-20 15:27
 */
public class _207_canFinish {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] indegrees = new int[numCourses];
        List<List<Integer>> adjacency = new LinkedList<>();//邻接表
        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++)
            adjacency.add(new LinkedList<>());

        for (int[] p : prerequisites) {
            indegrees[p[0]]++;
            adjacency.get(p[1]).add(p[0]);
        }

        for (int i = 0; i < numCourses; i++)
            if (indegrees[i] == 0) queue.add(i);

        while (!queue.isEmpty()) {
            Integer pre = queue.poll();
            numCourses--;
            for (Integer cur : adjacency.get(pre)) {
                indegrees[cur]--;
                if (indegrees[cur] == 0) queue.add(cur);
            }
        }
        return numCourses == 0;
    }
}
